package com.dubbo.interceper;

import com.dubbo.common.redis.RedisDao;
import com.dubbo.common.result.ResultInfo;
import com.dubbo.common.security.SecurityUtils;
import com.dubbo.common.security.bean.UserBean;
import com.dubbo.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理器拦截器
 * @author
 *
 */
@Component
public class HandlerInterceptorCustom implements HandlerInterceptor  {
	
	@Resource
	private RedisDao redisDao;
	@Value("${shiro.session.timeout:604800}")
	private long userSeconds;
	//获取客户端ip的方法
	private String getIp(HttpServletRequest request){
		String ip = request.getLocalAddr();
		Logger log4jLogger = Logger.getLogger(this.getClass());
		log4jLogger.info("获取客户端的ip>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		log4jLogger.info(ip==null?"无法获取请求的ip":ip);
		log4jLogger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取客户端的ip");
		
		if(!StringUtils.isNotBlank(ip) || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		
		if (!StringUtils.isNotBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		
		//通过nginx反向代理环境下获取ip的
		if(!StringUtils.isNotBlank(ip) || "unknown".equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	//请求前拦截
	/**
	 * 对非本地的ip请求进行拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<拦截器启动<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
		/*String scheme = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String path = request.getContextPath();
        String basePath = scheme + "://" + serverName + ":" + port + path;
        request.setAttribute("basePath", basePath);
        System.out.println("basePath>>>>>>>>>>>>>>>>>>>>");
        System.out.println("basePath="+basePath);
        System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<basePath");*/
		//设置跨域
		response = this.checkCrossDomain(request, response);
		String userNum = request.getHeader(ResultInfo.USERTOKEN);
		//校验用户是否在线
		request = this.checkOnline(request, userNum);
		return true;
	}
	
	/**
	 * 设置跨域
	 * @author lianglie
	 * @date 2018年12月9日 下午7:25:29
	 * @param request
	 * @param response
	 * @return
	 */
	private HttpServletResponse checkCrossDomain(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,userkey");
		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		response.setHeader("Access-Control-Allow-Credentials", "true");
		return response;
	}
	
	/**
	 * 校验用户是否在线
	 * @author lianglie
	 * @date 2018年12月9日 下午7:20:59
	 * @param request
	 * @param userNum
	 * @return
	 * @throws Exception
	 */
	private HttpServletRequest checkOnline(HttpServletRequest request, String userNum) throws Exception {
		if(StringUtils.isBlank(userNum)) {
			request.setAttribute(ResultInfo.USERTOKEN, null);
			return request;
		}
		//(狮盾项目-chenluqiang)从redis中获取用户信息
		UserBean userBean = (UserBean) SecurityUtils.getUserBean2(redisDao,userNum);
		User user = (User) userBean.getUserObj();
		if(user!=null && user.getId()!=null && user.getUserstatus()== 1) {
			//单方登录
			this.checkOneLogin(user,userNum,userBean.getRegistrationId());
			request.setAttribute(ResultInfo.USERTOKEN, user);
		}else {
			request.setAttribute(ResultInfo.USERTOKEN, null);
		}
		return request;
	}
	
	/**
	 * 单方登录
	 * @author chenluqiang
	 * @date 2019年4月1日 下午4:32:20 
	 * @param user
	 * @param userNum
	 */
	private void checkOneLogin(User user, String userNum, String registrationId) throws Exception {
		/*if(registrationId!=null&&StringUtils.isNotBlank(registrationId)) {
			String key = RedisConstant.getKey(ResultInfo.USER_CODE_KEY,user.getId());
			if(redisDao.exist(key)) {
				 String newRegistrationId = redisDao.get(key);
				if(newRegistrationId!=null&&StringUtils.isNotBlank(newRegistrationId)) {
					if(!newRegistrationId.equals(registrationId)) {
						redisDao.delete(userNum);
						throw new AjaxCheckError("您的账号已在其它地方登陆，若不是本人操作，请注意账号安全！");
					}
				}
			}
		}*/
	}
	//响应后拦截1
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView mav) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
	
	
}
